package com.raywang.pos.ui.fragment;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.raywang.pos.R;
import com.raywang.pos.bean.Goods;
import com.raywang.pos.db.DataBase;
import com.raywang.pos.ui.adapter.AllGoodsAdapter;
import com.raywang.pos.ui.adapter.GoodsAdapter;
import com.raywang.pos.ui.adapter.NumberKeyAdapter;
import com.raywang.pos.util.UIHelp;
import com.raywang.pos.view.EnhanceOnClickListener;
import com.raywang.pos.view.HeightImageView;
import com.raywang.pos.view.RayGridView;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.text.DecimalFormat;
import java.util.ArrayList;

/**
 * 销售的Fragment
 * @author Ray
 * @date 2015年6月26日10:50:49
 * @version 1.0
 */
public class SaleFragment extends BaseFragment {
	private EditText code;
    /** 显示销售的商品的ListView*/
	private SwipeMenuListView goods;

	private DataBase dao;

	private GoodsAdapter adapter;

	private View.OnClickListener listener;
    /** 模拟键盘的按键GridView*/
    private RayGridView gridView;
    /** 模拟键盘的按键适配器*/
    private NumberKeyAdapter keyAdapter;

    private Button pay;
    private Button cancel;

    /** 触摸模式的GridView*/
    private GridView allGoods;
    /** 输入模式的布局*/
    private View keyLayout;
    private AllGoodsAdapter allGoodsAdapter;

    private AlertDialog editDialog;

    private DecimalFormat df = new DecimalFormat("0.00");

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_sale, container,false);
		iniView(view);
		return view;
	}

	@Override
	protected void iniView(View view) {


		view.findViewById(R.id.ok).setOnClickListener(this);
		code = (EditText) view.findViewById(R.id.code);


        iniSwipeMenuListView(view);
		cancel = (Button) view.findViewById(R.id.cancel);
        cancel.setOnClickListener(this);

        pay = (Button) view.findViewById(R.id.pay);
        pay.setOnClickListener(listener);

        gridView = (RayGridView) view.findViewById(R.id.numbers);

        keyAdapter = new NumberKeyAdapter(getActivity(),new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                code.setText(code.getText().toString() + keyAdapter.getItem(v.getId()));
                code.setSelection(code.getText().toString().length());
//				Goods goods = dao.findByNumberOrCode(code.getText().toString());
//				if(goods != null){
//					adapter.addGoods(goods);
//					pay.setText("支付("+adapter.getMoney()+")");
//					cancel.setText("取消("+adapter.getAllCount()+")");
//					code.setText("");
//				}

            }
        });
        gridView.setAdapter(keyAdapter);
        view.findViewById(R.id.del).setOnClickListener(this);

		code.setOnKeyListener(new View.OnKeyListener() {

			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
					click(R.id.ok);
				}
				return false;
			}
		});

		adapter = new GoodsAdapter(getActivity(),new ArrayList<Goods>());
		goods.setAdapter(adapter);

		dao = new DataBase(getActivity());

        allGoods = (GridView) view.findViewById(R.id.allGoods);
        keyLayout = view.findViewById(R.id.keyLayout);

        allGoods.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                adapter.addGoods(allGoodsAdapter.getItem(position));
                onGoodsCountChage();
            }
        });
		super.iniView(view);

	}



    public void onGoodsCountChage(){
        if(adapter == null || adapter.getCount() == 0){
            pay.setText("支付");
            cancel.setText("取消");
        }else{
            pay.setText("支付("+adapter.getMoney()+")");
            cancel.setText("取消("+adapter.getAllCount()+")");
        }
    }

    /**
     * 初始化准备销售的商品的展示View（SwipeMenuListView）
     */
    private void iniSwipeMenuListView(View view){
        goods = (SwipeMenuListView) view.findViewById(R.id.goods1);
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {



                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        getActivity());
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                        0x3F, 0x25)));
                // set item width
                deleteItem.setWidth(UIHelp.dp2px(90,getActivity()));
                // set a icon
                deleteItem.setIcon(R.drawable.ic_delete);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };
        goods.setMenuCreator(creator);
        goods.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int i, SwipeMenu swipeMenu, int i2) {
                adapter.deleteGoods(i);
                onGoodsCountChage();
                return false;
            }
        });

        goods.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                showDialog(adapter.getItem(position));
            }
        });
    }

	@Override
	protected void click(int id) {
		switch (id){
			case R.id.ok:
				String scode = code.getText().toString();
				if("".equals(scode)){
					return ;
				}
				Goods goods = dao.findByNumberOrCode(scode);
				code.setText("");
				if(goods != null){
					adapter.addGoods(goods);
                    onGoodsCountChage();
				}else{
					UIHelp.toast(getActivity(),"商品不存在");
				}
				break;
            case R.id.del:
                String str = code.getText().toString();
                if(str.length() >= 1){
                    str = str.substring(0,str.length() - 1);
                }
                code.setText(str);
                code.setSelection(str.length());
                break;
			case R.id.cancel:
				adapter.clean();
                onGoodsCountChage();
				break;
		}
		super.click(id);
	}


	public void setListener(View.OnClickListener listener) {
		this.listener = listener;
	}

    public boolean canPay(){
        if(adapter != null && adapter.getCount() > 0){
            return true;
        }
        return false;
    }

    public void changeKeyOrTouch(boolean showKey){
        if(showKey){
            keyLayout.setVisibility(View.VISIBLE);
            allGoods.setVisibility(View.GONE);
        }else{
            keyLayout.setVisibility(View.GONE);
            allGoods.setVisibility(View.VISIBLE);
            if(allGoodsAdapter == null){
                allGoodsAdapter = new AllGoodsAdapter(getActivity(),dao.findAll());
                allGoods.setAdapter(allGoodsAdapter);
            }
        }
    }


    public GoodsAdapter getGoodsApdater(){
        if(adapter != null){
            return adapter;
        }
        return null;
    }

    ///////////////////////////////显示修改商品的Dialog的一些东西/////////////////////////
    private RayGridView keys1;
    /** 商品图片的控件*/
    private ImageView img;
    /** 商品名称*/
    private TextView goodsName;
    private EditText discount;
    private EditText nowMoney;
    private TextView price;
    private TextView allMoney;
    private TextView count;
    private Goods editGoods;
    /** 当前editText焦点的控件*/
    private EditText focusEdit;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            focusEdit.setSelection(0,focusEdit.getText().length());
        }
    };
    private View.OnTouchListener editTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == KeyEvent.ACTION_DOWN) {
                v.requestFocus();
                if (focusEdit != v) {
                    EditText temp = (EditText) v;

                    if (temp.getTag() == null) {
//                        handler.sendEmptyMessageAtTime(1, 200);
                        temp.setSelection(0, temp.getText().length());
//                        focusEdit.setSelection(focusEdit.getText().length());
                        focusEdit = temp;
                    } else {
                        focusEdit = temp;
                        focusEdit.setSelection(focusEdit.getText().length());
                    }
                    return true;
                }else{
                    return false;
                }

            }
            return true;
        }
    };
    private EnhanceOnClickListener editListener = new EnhanceOnClickListener() {
        @Override
        public void click(int id) {
            switch (id){
                case R.id.add:
                    countChange(editGoods.getCount() + 1);
                    break;
                case R.id.mins:
                    if(editGoods.getCount() >= 1){
                        countChange(editGoods.getCount() - 1);
                    }
                    break;
                case R.id.ok:
                    adapter.setGoods(editGoods);
                    discount.setTag(null);
                    nowMoney.setTag(null);
                    onGoodsCountChage();
                    editDialog.dismiss();
                    break;
                case R.id.del:
                    String str = focusEdit.getText().toString();
                    if(str.isEmpty() || focusEdit.getSelectionStart() == 0){
                        return;
                    }
                    int select = focusEdit.getSelectionStart() ;
                    String one = str.substring(0,select - 1);
                    String two = str.substring(focusEdit.getSelectionStart(),str.length());
                    focusEdit.setText(one+two);
                    focusEdit.setSelection(select - 1);
                    sumPriceAndDiscount();
                    break;
            }
        }
    };

    private void countChange(int tempCount){
        count.setText(""+tempCount);
        allMoney.setText(""+tempCount * editGoods.getPrice());
        editGoods.setCount(tempCount);
    }



    private void showDialog(Goods goods){
        if(editDialog == null){
            editDialog = new AlertDialog.Builder(getActivity()).create();
            editDialog.show();
            Window window = editDialog.getWindow();
            window.setContentView(R.layout.dialog_editgoods);
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.width = UIHelp.getWidth(getActivity()) - 20;
            lp.height = UIHelp.getHeight(getActivity()) - 20;
            window.setAttributes(lp);
            keys1 = (RayGridView) window.findViewById(R.id.numbers);
            img = (ImageView) window.findViewById(R.id.img);
            keys1.setAdapter(new NumberKeyAdapter(getActivity(),new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(focusEdit.getTag() == null || focusEdit.getText().toString().equals("0")){
                        focusEdit.setText(""+keyAdapter.getItem(v.getId()));
                        nowMoney.setTag("false");
                        discount.setTag("false");
                    }else {
                        focusEdit.setText(focusEdit.getText().toString() + keyAdapter.getItem(v.getId()));
                    }
                    focusEdit.setSelection(focusEdit.getText().toString().length());
                    //计算
                    sumPriceAndDiscount();
                }
            }));
            goodsName = (TextView) window.findViewById(R.id.goodsName);
            discount = (EditText) window.findViewById(R.id.discount);
            nowMoney = (EditText) window.findViewById(R.id.now_price);
            count = (TextView) window.findViewById(R.id.count);
            price = (TextView) window.findViewById(R.id.price);
            allMoney = (TextView) window.findViewById(R.id.allmoney);
            count = (TextView) window.findViewById(R.id.count);

            discount.setOnTouchListener(editTouchListener);
            nowMoney.setOnTouchListener(editTouchListener);
            window.findViewById(R.id.add).setOnClickListener(editListener);
            window.findViewById(R.id.mins).setOnClickListener(editListener);
            window.findViewById(R.id.ok).setOnClickListener(editListener);
            window.findViewById(R.id.del).setOnClickListener(editListener);
        }
        goodsName.setText(goods.getName());
        price.setText(""+goods.getPrice());
        allMoney.setText(""+goods.getCount()*goods.getPrice());
        discount.setText(""+(int)((double)goods.getPrice() / (double)goods.getOldPrice()*100) );
        nowMoney.setText(""+goods.getPrice());
        count.setText(""+goods.getCount());
        editGoods = goods;
        focusEdit = discount;
        focusEdit.requestFocus();
        focusEdit.setSelection(0,focusEdit.getText().length());
        editDialog.show();
        discount.setSelection(0,discount.getText().length());
    }

    /**
     * 重新计算价格和折扣
     */
    private void sumPriceAndDiscount(){
        if(focusEdit == discount){
            //是折扣的，计算现价
            if(discount.getText().toString().isEmpty()){
                nowMoney.setText("0");
                discount.setText("0");
            }else {
                int dis = Integer.parseInt(discount.getText().toString());
                double money = ((double) dis/ 100) * editGoods.getOldPrice();
                nowMoney.setText("" + df.format(money));
            }
        }else{
            if(nowMoney.getText().toString().isEmpty()){
                discount.setText("0");
                nowMoney.setText("0");
            }else {
                double price = Double.parseDouble(nowMoney.getText().toString());
                int dis = (int) (price / editGoods.getOldPrice()  * 100);
                discount.setText("" + dis);
            }
        }
        editGoods.setPrice(Double.parseDouble(nowMoney.getText().toString()));
    }
}
